/*
 * Copyright (C) 2012  E-dance Studio Harbin Institute of Technology 
 * Project:campusmobile
 * Author: 初楷博
 * Create Date: 2012-5-24下午11:41:31
 */
package hit.edance.campusmobile.chat.activity;

import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smackx.packet.VCard;

import hit.edance.campusmobile.chat.ActivityWelcome;
import hit.edance.campusmobile.chat.R;
import hit.edance.campusmobile.chat.database.DBChatHistoryHelper;
import hit.edance.campusmobile.chat.model.ActivityKiller;
import hit.edance.campusmobile.chat.model.FriendsManager;
import hit.edance.campusmobile.chat.model.MyChatManager;
import hit.edance.campusmobile.chat.model.OfflineManager;
import hit.edance.campusmobile.chat.service.CampusMobileService;
import hit.edance.campusmobile.chat.util.ConstantUtil;
import hit.edance.campusmobile.chat.util.PictureUtil;
import hit.edance.campusmobile.chat.util.SharedPreferencesHelper;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TabActivity;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.CompoundButton;
import android.widget.TabHost;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;


/**   
 * 主界面
 * 
 * @Project campusmobile
 * @Package hit.edance.campusmobile.chat.activity
 * @Class ActivityTab
 * @Date 2012-5-24 下午11:41:31
 * @author 初楷博
 * @version 1.0
 * @since 1.0
 */
public class ActivityTab extends TabActivity implements OnCheckedChangeListener{

	public static final int ITEM0 = Menu.FIRST;
	public static final int ITEM1 = ITEM0 + 1;
	
	private TabHost myTabHost = null;
	public static NotificationManager notificationManager;
	public static final int DIALOG_SIMPLE_CONFIRM = 0;
	
	private static final String TAG  = ActivityTab.class.getSimpleName();
	/**
	 * 标志，从图库获取头像
	 */
	private static final int FLAG_PICK_PHOTO = 1001;
	
	/**
	 * 标志，拍照获取头像
	 */
	private static final int FLAG_CAPTURE_PHOTO = 1002;
	
	/**
	 * 标志，图片截取完毕
	 */
	private static final int FLAG_CROP_PHOTO = 1003;
	
	/* @see android.app.Activity#onCreate(android.os.Bundle)
	 *onCreate
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		ActivityKiller.addActivity(hashCode(), this);
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.chat_tab);
		myTabHost = getTabHost();
		MyChatManager.setActivityTab(this);
		initActivity();
		OfflineManager.handleOfflineMessages(new DBChatHistoryHelper(this));
		MyChatManager.startListener();
	}
	

	/**
	 * 初始化activity
	 */
	private void initActivity() {
		notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
		ImageView    
			headImage = (ImageView)findViewById(R.id.headimage),
			statusImage = (ImageView)findViewById(R.id.statusimage),
			switchAccount = (ImageView)findViewById(R.id.switchAccount);
		switchAccount.setOnClickListener(new OnClickListener(){

			public void onClick(View v) {
				showDialog(DIALOG_SIMPLE_CONFIRM);
			}
			
		});
		TextView 
			nameTV = (TextView)findViewById(R.id.name),
			signatureTV = (TextView)findViewById(R.id.signature);
		VCard vcard = new VCard();
		try {
			vcard.load(CampusMobileService.connection);
		} catch (XMPPException e) {
			e.printStackTrace();
		}
		nameTV.setText(vcard.getNickName() == null ? vcard.getJabberId() : vcard.getNickName());
		//TODO
		signatureTV.setText(vcard.getEmailHome() == null ? "我很懒" : vcard.getEmailHome());
		Bitmap bmp = PictureUtil.getPicFromBytes(vcard.getAvatar(),null);
		if(bmp != null)
			headImage.setImageBitmap(bmp);
		else
			headImage.setImageDrawable(getResources().getDrawable(R.drawable.chat_ic_contact_picture));
		final int statusImageSource = ActivityLogin.statusImg[Integer.parseInt(ConstantUtil.STATUS)];
		statusImage.setImageDrawable(getResources().getDrawable(statusImageSource));
		
		
		Intent intent0 = new Intent(this, ActivityLatelyContact.class);
		Intent intent1 = new Intent(this, ActivityFriends.class);
		Intent intent2 = new Intent(this, ActivityFriends.class);
		
		initRadios();
		
		myTabHost.addTab(myTabHost.newTabSpec("tab1")
				.setIndicator("tab1", getResources().getDrawable(R.drawable.chat_ic_menu_cc))
				.setContent(intent0));
		myTabHost.addTab(myTabHost.newTabSpec("tab2")
				.setIndicator("tab2", getResources().getDrawable(R.drawable.chat_ic_menu_friendslist))
				.setContent(intent1));
		myTabHost.addTab(myTabHost.newTabSpec("tab3")
				.setIndicator("tab3", getResources().getDrawable(R.drawable.chat_ic_menu_allfriends))
				.setContent(intent2));
		//myTabHost.setBackgroundResource(R.drawable.background);
		
		myTabHost.setCurrentTabByTag("tab2");
	}

	/**
	* 初始化顶部按钮
	*/
	private void initRadios() {
		((RadioButton) findViewById(R.id.radio_button0)).setOnCheckedChangeListener(this);
		((RadioButton) findViewById(R.id.radio_button1)).setOnCheckedChangeListener(this);
		((RadioButton) findViewById(R.id.radio_button2)).setOnCheckedChangeListener(this);
	}
	/**
	* 切换模块
	*/
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		if (isChecked) {
		    switch (buttonView.getId()) {
		    case R.id.radio_button0:
		        this.myTabHost.setCurrentTabByTag("tab1");
		        break;
		    case R.id.radio_button1:
		        this.myTabHost.setCurrentTabByTag("tab2");
		        break;
		    case R.id.radio_button2:
		        this.myTabHost.setCurrentTabByTag("tab3");
		        break;
		    }
		}
	}
	
	/* @see android.app.Activity#onCreateDialog(int)
	 *onCreateDialog
	 */
	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog = null;
		Builder builder = new AlertDialog.Builder(this);
		switch (id) {
		case DIALOG_SIMPLE_CONFIRM:
			dialog = builder
					.setTitle(
							getResources().getString(
									R.string.chat_switchaccount))
					.setPositiveButton(
							getResources().getString(R.string.chat_confirm),
							new DialogInterface.OnClickListener(){

								public void onClick(DialogInterface dialog,
										int which) {
									//TODO
									
									
									SharedPreferencesHelper sp = new SharedPreferencesHelper(ActivityTab.this);
									sp.setValueByKey("account", null);
									sp.setValueByKey("password", null);
									sp.setValueByKey("status", null);
									startActivity(new Intent(ActivityTab.this,ActivityWelcome.class));
									MyChatManager.close();
									FriendsManager.close();
									ActivityKiller.killAll();
									CampusMobileService.connection.disconnect();
								}

								
							})
					.setNegativeButton(
							getResources().getString(R.string.chat_cancel),
							null).create();
			break;
		default:
			break;
		}
		return dialog;
	}


	public void notifyChat(String jabberId,String nickname, CharSequence tickerText){
		Notification notification = new Notification(R.drawable.chat_stat_notify_chat
				,tickerText
				,System.currentTimeMillis());
		notification.defaults |= Notification.DEFAULT_SOUND;
		notification.defaults |= Notification.DEFAULT_VIBRATE;
		Intent intent = new Intent(this, ActivityChat.class);
		intent.putExtra("jabberId", jabberId);
		intent.putExtra("nickname", nickname);
		notification.flags = Notification.FLAG_AUTO_CANCEL;
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		notification.setLatestEventInfo(this, nickname, tickerText, contentIntent);
		notificationManager.notify(0, notification);
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, ITEM0, 0, getResources().getString(R.string.chat_searchfriends));
		menu.findItem(ITEM0).setIcon(R.drawable.chat_ic_menu_search);
		menu.add(0,ITEM1,1,getResources().getString(R.string.chat_logout));
		menu.findItem(ITEM1).setIcon(R.drawable.chat_ic_lock_power_off);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()){
			case ITEM0:
				actionClickMenuItem0();
				break;
			case ITEM1:
				actionClickMenuItem1();
				break;
			default:
				break;
		}
		return super.onOptionsItemSelected(item);
	}
	/**
	 * 
	 */
	private void actionClickMenuItem1() {
		
	}


	/**
	 * 
	 */
	private void actionClickMenuItem0() {
		startActivity(new Intent(ActivityTab.this,ActivitySearchFriends.class));
		
	}


	/* @see android.app.Activity#onDestroy()
	 *onDestroy
	 */
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		ActivityKiller.killActivityByHashCode(hashCode());
	}
}
